import React, { useEffect, useState } from 'react'

import { Button } from 'antd-mobile'
import { Input, List, message } from 'antd'

import ServiceChat from '../../component/serviceChat'
import ClientChat from '../../component/clientChat'


import styles from './index.module.css'

//网络请求
import { postDialogue } from '../../utils/axiosRequest/api'


function Chat() {

    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //输入框
    const [inputValue, setInputValue] = useState('')
    //聊天记录数组
    const [chatData, setChatData] = useState(
        [
            {
                content: '你好~admin！我是你的专属ai助手',
                isServeChat: true,
            },
        ])

    //[]空数组相当于componentDidMount
    useEffect(() => {
        document.title = '专属助理';
        //返回的函数相当于unmountComponentAtNode
        return () => {

        }
    }, []);

    //监听chatData，有改变就滚动到底部
    useEffect(() => {
        rollToBottom()
    }, [chatData]);

    function onInputChange(e) {
        let value = e.target.value;
        setInputValue(value);
    }

    function rollToBottom() {
        const length = chatData.length;
        const listElement = document.getElementById('chat_item_' + (length - 1));
        listElement.scrollIntoView({ behavior: 'smooth' });
    }

    //点击发送
    function hitSend() {
        if (inputValue.length === 0) {
            messageApi.open({ type: 'error', content: '问题不能为空！' });
            return;
        }

        if (inputValue.length > 20) {
            messageApi.open({ type: 'error', content: '请输入20个字以内的问题！' });
            return;
        }
        //本地输入
        addDialogue(inputValue, false)
        setInputValue('');
        //发起请求
        document.title = '正在为您解答中...';
        const params = new Map()
        params.set('problem', inputValue)
        postDialogue(params)
            .then(response => {
                const data = response.data
                if (data.code === 1000) {
                    addDialogue(data.data, true);
                } else {
                    messageApi.open({ type: 'error', content: data.des });
                }
                document.title = '专属助理';
            })
            .catch(error => {
                document.title = '专属助理';
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //添加对话
    function addDialogue(str, isServeChat) {
        const data = {
            content: str,
            isServeChat: isServeChat,
        }
        //数组的追加
        setChatData(prevState => [...prevState, data]);
        rollToBottom();
    }

    function getitem(item, index) {
        if (item.isServeChat) {
            return <ServiceChat content={item.content}></ServiceChat>
        } else {
            return <ClientChat content={item.content}></ClientChat>
        }
    }

    return (
        <div className={styles.app}>
            <div className={styles.body} >
                {contextHolder}
                <div style={{ width: '100vw', height: '90vh', overflowY: 'scroll' }} >
                    <List id={'aaaaa'} split={false}
                        itemLayout="horizontal"
                        dataSource={chatData}
                        renderItem={(item, index) => (
                            <List.Item id={'chat_item_' + index}>
                                {getitem(item, index)}
                            </List.Item>
                        )}
                    />
                </div>
            </div>
            <div className={styles.bottom_input}>
                <div className={styles.input_body}>
                    <Input className={styles.input} maxLength={'20'} size="large" placeholder="请输入..." value={inputValue} onChange={onInputChange} />
                    <Button className={styles.send} size='mini' color='primary' fill='solid' onClick={hitSend}>发送</Button>
                </div>
            </div>
        </div>
    )
}

export default Chat;
